package com.um.jdy.platform.platform.manager;

import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.code.PlatformCode;
import com.um.jdy.common.platform.entity.dto.CompanyDTO;
import com.um.jdy.common.platform.entity.dto.CompanyUserDTO;
import com.um.jdy.common.platform.entity.po.*;
import com.um.jdy.common.platform.entity.vo.CompanyUserVO;
import com.um.jdy.common.platform.entity.vo.CompanyVO;
import com.um.jdy.common.platform.service.CompanyRoleService;
import com.um.jdy.common.platform.service.CompanyService;
import com.um.jdy.common.platform.service.CompanyUserRoleService;
import com.um.jdy.common.platform.service.CompanyUserService;
import com.um.jdy.platform.platform.entity.vo.UserRoleItemVO;
import com.um.jdy.platform.user.service.SessionUserService;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.DesEncrypter;
import com.um.springboot.starter.utils.RSAUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;

/**
 * 管理类：管理员用户表
 */
@Component
public class CompanyUserManager extends BaseManager<CompanyUserService> {

    @Autowired
    CompanyRoleService companyRoleService;

    @Autowired
    CompanyUserRoleService companyUserRoleService;

    @Autowired
    SessionUserService sessionUserService;

    /**
     * 查询分页
     * @param params
     * @return
     */
    public Response<Page<CompanyUserVO>> getPage(@RequestBody PageParams params){
        Page<CompanyUser> page = new Page();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());

        params.getCondition().put("orderby","create_time desc");
        params.getCondition().put("com_id",getComId());
        params.getCondition().put("is_master",YesOrNo.No.name());
        page = service.getPage(page,params.getProperties(), params.getValues(),params.getRangeEntitys(),params.getOrderNames(),params.getSortOns());

        Page<CompanyUserVO> pageVo = new Page();
        pageVo.setPageSize(page.getPageSize());
        pageVo.setPageNo(page.getPageNo());
        pageVo.setTotalCount(page.getTotalCount());
        pageVo.setResult(UMBeanUtils.copyBeanList(page.getResult(),CompanyUserVO.class));

        return Response.success(pageVo);
    }

    /**
     * 查询用户角色列表
     * @param userId
     * @return
     */
    public Response<List<UserRoleItemVO>> getUserRoles(String userId){

        List<CompanyRole> listRoles = companyRoleService.getListByLike("name","%","create_time","desc");
        List<UserRoleItemVO> userRoles = UMBeanUtils.copyBeanList(listRoles,UserRoleItemVO.class);

        if(userRoles.size() == 0){
            return Response.success(userRoles);
        }

        List<CompanyUserRole> lstSelected = companyUserRoleService.getList("platform_company_user_id",userId);

        for(UserRoleItemVO item : userRoles){
            for(CompanyUserRole role : lstSelected){
                if(item.getPlatformCompanyRoleId().equals(role.getPlatformCompanyRoleId())){
                    item.setSelected(true);
                    break;
                }
            }
        }
        return Response.success(userRoles);
    }

    /**
     * 新增用户及角色
     * @param user
     * @param roleIds
     * @return
     */
    @Transactional
    public Response addEntity(CompanyUserDTO user, List<String> roleIds){
        if(service.getEntity("mobile",user.getMobile()) != null){
            return Response.failed(PartnersCode.MobileExist);
        }

        if(roleIds.size() == 0){
            return Response.failed(PlatformCode.RolesNoSelected);
        }

        CompanyUser entity = UMBeanUtils.copyBean(user,CompanyUser.class);

        String pwd = RSAUtil.simpleDecrypt(user.getPassword());
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);

        entity.setIsMaster(YesOrNo.No.name());
        entity.setPassword(des.encrypt(pwd));
        entity.setComId(getComId());
        entity.setCreateTime(new Date());
        service.addEntity(entity);

        for(String roleId : roleIds){
            CompanyUserRole item = new CompanyUserRole();
            item.setPlatformCompanyRoleId(roleId);
            item.setPlatformCompanyUserId(entity.getPlatformCompanyUserId());
            companyUserRoleService.addEntity(item);
        }
        return Response.success();
    }

    /**
     * 修改用户及角色
     * @param user
     * @param roleIds
     * @return
     */
    @Transactional
    public Response updateEntity(String id, CompanyUserDTO user, List<String> roleIds){
        if(roleIds.size() == 0){
            return Response.failed(PlatformCode.RolesNoSelected);
        }

        CompanyUser entity = UMBeanUtils.copyBean(user,CompanyUser.class);
        entity.setMobile(null);//不能修改手机号码
        entity.setPlatformCompanyUserId(id);
        entity.setIsMaster(YesOrNo.No.name());
        entity.setCreateTime(new Date());
        service.updateEntity(entity);

        companyUserRoleService.delete("platform_company_user_id",id);
        for(String roleId : roleIds){
            CompanyUserRole item = new CompanyUserRole();
            item.setPlatformCompanyRoleId(roleId);
            item.setPlatformCompanyUserId(entity.getPlatformCompanyUserId());
            companyUserRoleService.addEntity(item);
        }
        return Response.success();
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    public Response resetPassword(String userId, String password){
        CompanyUser entity = service.getEntity(userId);
        if(entity == null){
            throw new ServiceException(PlatformCode.CompnayUserNotExist);
        }

        String pwd = RSAUtil.simpleDecrypt(password);

        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String encryptPwd = des.encrypt(pwd);
        if(encryptPwd.equals(entity.getPassword())){
            throw new ServiceException(PartnersCode.PwdSame);
        }

        entity.setPassword(encryptPwd);
        boolean result = service.update(entity);
        return result ? Response.success() : Response.failed();
    }

    @Transactional
    public Response delete(String id) {
        boolean result = this.service.delete(id);
        companyUserRoleService.delete("platform_company_user_id",id);
        return result ? Response.success() : Response.failed();
    }

    @Transactional
    public Response deleteIds(List<String> ids) {
        boolean result = service.deleteIds(ids);
        ids.stream().forEach(id -> {
            companyUserRoleService.delete("platform_company_user_id",id);
        });
        return result ? Response.success() : Response.failed();
    }

    public Response enable(String id, String enable) {
        CompanyUser entity = this.service.getEntity(id);
        if(entity == null){
            throw new ServiceException(PlatformCode.CompnayUserNotExist);
        }

        entity.setIsEnable(enable);
        boolean result = this.service.update(entity);
        return result ? Response.success() : Response.failed();
    }

}
